package com.hgw.gulimall.product.exception;

import com.hgw.common.exception.BizCodeEnume;
import io.renren.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Map;

/**
 * Data time:2022/3/18 15:58
 * StudentID:2019112118
 * Author:hgw
 * Description: 集中处理所有异常
 * @ControllerAdvice 统一处理异常
 * basePackages = "com/hgw/gulimall/product/controller"： 接收了由本模块controller层抛过来的异常
 * @RestControllerAdvice = @ResponseBody + @ControllerAdvice
 */
//@ResponseBody
//@ControllerAdvice(basePackages = "com/hgw/gulimall/product/controller")
@Slf4j
@RestControllerAdvice(basePackages = "com.hgw.gulimall.product.controller")
public class GulimallExceptionControllerAdvice {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleVaildException(MethodArgumentNotValidException e){
        log.error("数据校验出现问题{},异常类型{}",e.getMessage(),e.getClass());
        BindingResult result = e.getBindingResult();

        Map<String,String> errorMap = new HashedMap();
        result.getFieldErrors().forEach(fieldError -> {
            errorMap.put(fieldError.getField(),fieldError.getDefaultMessage());
        });
        return R.error(BizCodeEnume.VALID_EXCEPTION.getCode(),BizCodeEnume.VALID_EXCEPTION.getMsg()).put("data",errorMap);
    }

    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable throwable) {
        return R.error(BizCodeEnume.VALID_EXCEPTION.getCode(),BizCodeEnume.VALID_EXCEPTION.getMsg());
    }
}
